package it.polimi.meteocal_pappalardo_sacchi.bean;

import it.polimi.meteocal_pappalardo_sacchi.entity.*;

import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * Created by Alessandro on 09/01/15.
 */
@Stateless
public class ScheduleBean implements Serializable {

    private static final int MAX_DAYS = 15;
    @Inject
    ForecastBean forecastBean;
    @Inject
    EventManager eventManager;
    @Inject
    NotificationManager notificationManager;
    @Inject
    WeatherManager weatherManager;

    @Schedule(dayOfWeek = "*", persistent = false, timezone = "Europe/Paris")
    private void retrieveForecastForOutdoorEventsStartingFromTomorrowOnwards() {
        for (Event event : eventManager.findOutdoorEventsStartingFromTomorrowTo15Days()) {
            if (forecastBean.retrieveForecastForEvent(event)) {
                eventManager.edit(event);
            }
        }
    }

    //invio le notifiche all'1 in modo da avere (ampio) tempo per scaricare le previsioni a mezzanotte
    @Schedule(dayOfWeek = "*", hour = "1", timezone = "Europe/Paris")
    public void notifyGuestOfAllTomorrowEventsOfBadWeather() {
        List<Event> ev = eventManager.findEventsStartingIn24HoursWithBadWeather();
        for (Event e : ev) {
            notificationManager.sendBadWeatherNotification(e);
        }
    }

    /**
     * In case of bad forecast, suggests the closer date of good weather to the creator of an event within three days
     */
    @Schedule(dayOfWeek = "*", timezone = "Europe/Paris")
    public void suggestReschedulingToCreator() {
        List<Event> ev = eventManager.findEventsWithBadWeatherStartingIn3Days();        
        for (Event e : ev) {
            notificationManager.sendBadWeatherNotificationWithSuggestion(e);
        }
    }

    @Schedule(dayOfWeek = "*", persistent = false, timezone = "Europe/Paris")
    private void retrieveForecastForOutdoorOngoingEventsEndingInMoreThan15Days() {
        List<Event> allOutdoorOngoingEvents = eventManager.findAllOutdoorOngoingEvents();
        ZoneId zone = ZoneId.of("Europe/Paris");
        for (Event e : allOutdoorOngoingEvents) {
            if (ChronoUnit.DAYS.between(LocalDate.now(zone), e.getEndingDate().toLocalDate()) > MAX_DAYS) {
                forecastBean.retrieveForecastForEvent(e);
            }
        }
    }
}
